package cn.myjerry.test.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import cn.myjerry.test.reflection.bean.User;

/**
 * 通过反射API动态的操作：构造器、方法、属性
 * @author zpon
 *
 */
@SuppressWarnings("all")
public class Demo03 {
	public static void main(String[] args) throws Exception {
		String path = "cn.myjerry.test.reflection.bean.User";
		Class<User> clazz = (Class<User>) Class.forName(path);
		
		// 通过反射API调用构造方法，构造对象
		User u = clazz.newInstance();
		
		Constructor<User> c = clazz.getConstructor(int.class, int.class, String.class);
		
		User u2 = c.newInstance(1001, 16, "Jerry");
		System.out.println(u2.getName());
		
		// 通过反射API调用普通方法
		User u3 = clazz.newInstance();
		Method method = clazz.getDeclaredMethod("setName", String.class);
		method.invoke(u3, "Tom");
		System.out.println(u3.getName());
		
		// 通过反射API操作属性
		User u4 = clazz.newInstance();
		Field field = clazz.getDeclaredField("Name");
		field.setAccessible(true);	// 这个属性不用做安全检查了，可以直接访问
		field.set(u4, "Davy");
		System.out.println(u4.getName());
		System.out.println(field.get(u4));
		
	}
}
